package com.carnation.service.impl;

import java.io.File;
import java.util.Iterator;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.carnation.bean.User;
import com.carnation.service.UserService;
import com.carnation.utils.MenuFileUtril;

public class UserServiceImpl implements UserService{
	
	Logger logger = Logger.getLogger(UserServiceImpl.class);
	MenuFileUtril util = new MenuFileUtril();
	
	@Override
	public User checkLogin(String username, String password) {
		String userFilePath = util.getUserInfoDBNameWithPath();
		File file = new File(userFilePath);
		if(!file.exists()){
			logger.error("找不到用户文档");
			return null;
		}
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		try {
			Document document = reader.read(file);
			Element root = document.getRootElement();
			@SuppressWarnings("rawtypes")
			Iterator users = root.elementIterator("user");
			User targer = null;
			while(users.hasNext()){
				Element user = (Element)users.next();
				String name = user.attributeValue("name");
				String passwd = user.attributeValue("password");
				String role = user.attributeValue("role");
				if(name.equals(username)&& passwd.equals(password)){
					targer = new User(name, password, role);
					return targer;
				}
			}
			return null;
		} catch (DocumentException e) {
			logger.error("读取用户文档失败",e);
			return null;
		}
	}

	@Override
	public User checkLogin(User user) {
		if(user == null){
			return null;
		}
		return checkLogin(user.getUserName(),user.getPassword());
	}
	
	@Override
	public boolean checkPriviledge(User user,String enter){
		if(user == null){
			return false;
		}
		String role = user.getRole();
		if(role.equals("manager")){
			return true;
		}
		else{
			if(role.equals("sysuser") && enter.equals("down")){
				return true;
			}
			else{
				return false;
			}
		}
	}
}
